package org.ktx.osr.util

import org.ktx.osr.ui.AppSettings

object SettingsUtils {
    
    /**
     * 解析分辨率字符串，返回宽度和高度
     */
    fun parseResolution(resolution: String, defaultWidth: Int = 1920, defaultHeight: Int = 1080): Pair<Int, Int> {
        return when (resolution) {
            "720p" -> Pair(1280, 720)
            "1080p" -> Pair(1920, 1080)
            "1440p" -> Pair(2560, 1440)
            else -> {
                // 尝试解析"原画"格式，如"原画(1920x1080)"
                if (resolution.startsWith("原画(") && resolution.endsWith(")")) {
                    val sizeStr = resolution.substring(3, resolution.length - 1) // 移除"原画("和")"
                    val parts = sizeStr.split("x")
                    if (parts.size == 2) {
                        try {
                            val width = parts[0].toInt()
                            val height = parts[1].toInt()
                            return Pair(width, height)
                        } catch (e: NumberFormatException) {
                            // 解析失败，使用默认值
                        }
                    }
                }
                Pair(defaultWidth, defaultHeight)
            }
        }
    }
    
    /**
     * 解析帧率字符串，返回帧率数值
     */
    fun parseFrameRate(frameRate: String, default: Int = 30): Int {
        return when (frameRate) {
            "15 fps" -> 15
            "24 fps" -> 24
            "30 fps" -> 30
            "60 fps" -> 60
            else -> {
                // 尝试从字符串中提取数字
                val regex = "\\d+".toRegex()
                val match = regex.find(frameRate)
                match?.value?.toIntOrNull() ?: default
            }
        }
    }
    
    /**
     * 解析视频格式，返回MediaRecorder输出格式
     */
    fun parseVideoFormat(videoFormat: String): Int {
        return when (videoFormat.uppercase()) {
            "MP4" -> android.media.MediaRecorder.OutputFormat.MPEG_4
            "MOV" -> android.media.MediaRecorder.OutputFormat.WEBM
            else -> android.media.MediaRecorder.OutputFormat.MPEG_4
        }
    }
    
    /**
     * 根据设置获取视频编码比特率
     */
    fun getVideoBitrate(resolution: String, frameRate: Int): Int {
        val (width, height) = parseResolution(resolution)
        val pixels = width * height
        
        return when {
            pixels <= 1280 * 720 -> 2 * 1000 * 1000 // 2 Mbps for 720p
            pixels <= 1920 * 1080 -> 5 * 1000 * 1000 // 5 Mbps for 1080p
            pixels <= 2560 * 1440 -> 10 * 1000 * 1000 // 10 Mbps for 1440p
            else -> 15 * 1000 * 1000 // 15 Mbps for higher resolutions
        }
    }
}
